package com.jsyso.jadmin.common.utils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

public class ShiroUtils {

	/**
	 * 获取当前登录者对象
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getPrincipal(){
		Subject subject = getSubject();
		return (T) subject.getPrincipal();
	}
	
	/**
	 * 当前用户是否已经登录
	 * @return
	 */
	public static boolean isLogin() {
		return getPrincipal() != null;
	}
	
	/**
	 * 获取授权主要对象
	 */
	public static Subject getSubject(){
		return SecurityUtils.getSubject();
	}
	
	/**
	 * 获取Session
	 * @return
	 */
	public static Session getSession() {
		Subject subject = getSubject();
		Session session = subject.getSession(false);
		if(session == null) {
			session = subject.getSession();
		}
		return session;
	}
	
	/* ================= User Cache { ================= */
	
	@SuppressWarnings("unchecked")
	public static <T> T getCache(String key) {
		return (T) getCache(key, null);
	}
	
	public static Object getCache(String key, Object defaultValue) {
		Object obj = getSession().getAttribute(key);
		return obj == null ? defaultValue : obj;
	}
	
	public static void putCache(String key, Object value) {
		getSession().setAttribute(key, value);
	}
	
	public static void removeCache(String key) {
		getSession().removeAttribute(key);
	}
	
	/* ================= } ================= */
	
}
